from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView, ListCreateAPIView
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.permissions import IsAuthenticated

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework_jwt.views import JSONWebTokenAPIView, obtain_jwt_token, ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from goods.serializers import SKUSerializer
from users import constants
from users import serializers
from users.models import User


# ------------判断用户名是否存在-------------------
# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
# GET usernames/(?P<username>\w{5,20})/count/
from users.serializers import UserDetailSerializer, EmailSerializer, AddUserBrowsingHistorySerializer


class UsernameCountView(APIView):
    """
    以用户名数量来判断用户是否存在
    :param username: type: str
    :return {"username": username, "count": count}
    """
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        data = {
            'username': username,
            'count': count
        }
        return Response(data)


# -----------判断手机号是否存在-------------------
# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
# GET mobiles/(?P<mobile>1[3-9]\d{9})/count/
class MobileCountView(APIView):
    """
    以手机号数量来判断手机号是否存在
    :param mobile, type: str
    :return {"mobile": mobile, "count": count}
    """
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            'username': mobile,
            'count': count
        }
        return Response(data)


# ----------------------用户注册-------------------
# url(r'^users/$', views.UserView.as_view()),
# POST   /users/
class UserView(CreateAPIView):
    """
    传入参数:
        username    type: str
        password    type: str
        password2   type: str
        sms_code    type: str
        mobile      type: str
        allow       type: str
    返回数据: JSON格式
        id          type: int
        username    type: str
        mobile      type: str

    """
    # queryset =   # 这里并不需要查询
    serializer_class = serializers.CreateUserSerializer


# ------------------------------登  录------------------------------
# 在登录时会调用rest_framework_jwt.views中的obtain_jwt_token视图函数(继承JSONWebTokenAPIView,其实就是ObtainJSONWebToken类),在这个视图中对各种请求解析/验证(这里会执行如身份认证[如:方式登录功能]authenticat, 自定义jwt认证需重写此方法,其返回值为user等)/返回response,这里返回的数据由jwt_response_payload_handler方法返回,默认只返回token,故经常重写
# 这里登录采取自带登录类ObtainJSONWebToken
# 请配合readme笔记一同学习
"""
请求方式: POST /authorizatios/
请求参数: JSON或者表单  username(type: str)   password(type: str)
返回参数: JSON        username(type: str)     user_id(type: int)     token(type: str)
"""
# 由于自带jwt_response_payload_handler方法返回值只有token,即视图登录视图返回值只有token,因此需在urls.py中重写此方法,同时需对重写的方法进行配置JWT_AUTH


"""
# 如果需要对返回的json或者是request数据提前做一些处理(如验证码之类的业务),可以继承ObtainJSONWebToken类,重写post方法设置response或者提前处理request就可以了,当然了,注意路由
class ChangeObtainJSONWebToken(ObtainJSONWebToken):
    pass
"""

# --------------------------用户中心个人信息展示视图------------------------
# url(r'^user/$',views.UserDetailView.as_view()),
class UserDetailView(RetrieveAPIView):
    """
    用户详情,注: 访问视图必须要求用户已通过认证(即登录之后)
    GET /user/
    :return id/username/mobile/email/email_active
    """
    # queryset =   这里并不需要进行查询集
    serializer_class = UserDetailSerializer
    # 权限处理,访问视图必须要求用户已通过认证
    permission_classes = [IsAuthenticated]

    """
    视图中封装好的代码,是根据主键查询得到的对象,
    若要不根据主键查,而是获取登录的用户,那么只需重写get_object()方法
    """
    def get_object(self):
        return self.request.user


# url(r'^emails/$', views.EmailView.as_view()),
class EmailView(UpdateAPIView):
    """
    保存用户邮箱,并发送验证邮件,实际上就是更新用户信息
    PUT /email/
    请求参数: email
    返回数据: id   email
    """
    # 身份鉴定,只有用户登陆后才及你想嗯邮箱保存/验证
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    # 这里需要知道是哪个用户在进行邮箱验证,因此需要获得当前用户对象(如用户和邮箱的识别信息),而此时未提供主键,因此只能根据请求中的用户来查询,所以需重写get_object方法,但基于安全性考虑,不将这两个数据暴露在邮件链接中,而是需要进行签名处理,可采用itsdangerous
    def get_object(self, *args, **kwargs):
        return self.request.user

"""
url(r'^emails/verification/$', views.VerifyEmailView.as_view()),
当用户点击邮箱的链接时,进入到success_verify_email.html页面,在这个页面中将请求网址中用于验证的token发送给后端接口,由后端判断token的有效性(即该用户是否存在),然后生成对应的邮箱验证状态
GET /emails/verification/?token=xxx

注: 这里原本是修改对应用户的邮箱(激活)字段,本应是put请求,但是由于本项目中前端先写好了,因此这里采取前端的方式发送get请求
"""
class VerifyEmailView(APIView):
    """
    请求参数: 查询字符串   token
    返回数据: 验证处理结果  message
    """
    def get(self, request):
        # 获取token值(即获取谁需要验证哪个邮箱)
        token = request.query_params.get('token')
        if not token:
            return Response({
                'message': "缺少token"
            }, status=status.HTTP_400_BAD_REQUEST)
        # 验证token,其实就是取到对应的用户
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({
                'message': '无效链接'
            }, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({
                'message': "OK"
            })


class AddressViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet):  # 或者直接继承 class AddressViewSet(ModelViewSet):
    """用户地址增删改查"""
    serializer_class = serializers.UserAddressSerializer
    permission_classes = [IsAuthenticated]

    # 指定查询集
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """用户地址列表数据"""
        # get_queryset 返回视图使用的查询集
        queryset = self.get_queryset()
        # get_serializer 返回序列化器类
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """新增, 其实本方法还可直接写在序列化器中的create()中,只是在条件判断出改为直接跑异常raise"""
        # 检查用户地址数据数目,不能超过上线
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({
                'message': '保存地址数据已达上限'
            }, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """处理删除"""
        # get_object 返回详情视图所需的模型类数据对象,默认根据lookup_field参数(主键)来过滤queryset
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    # detail = True 表示action中要处理的视图资源对象是否通过url路径获取主键
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """设置默认地址, 实际上是修改default_address字段"""
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({
            'message': 'OK'
        }, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, *args, **kwargs):
        """修改标题"""
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        """
        或者不采取序列化器的方式,而是直接修改保存即可
        address = self.get_object()
        address.title = request.data.get('title')
        address.save()
        return Response({'title': address.title})
        """
        return Response(serializer.data)


"""
用户在访问每个商品详情页面时,都记录浏览历史记录
历史记录只需要保存多个商品的sku_id即可,而且需要保持添加sku_id的顺序,
这里采取redis中列表来保存数据,格式: 'history_用户id': [sku_id列表]
    ps:其实mysql数据库也行
"""
# class UserBrowsingHistoryView(CreateAPIView):
#     """
#     用户浏览历史记录的实现方式二
#     请求方式: POST /browse_histories/
#     请求参数: sku_id(int)
#     返回数据: sku_id(int)
#     """
#     permission_classes = [IsAuthenticated]
#
#     # 这里需要保存浏览记录,因此获得sku_id验证存在后就可以查询对应的sku信息,然后保存在数据库(这里采用redis,其他也行如mysql)中
#     serializer_class = AddUserBrowsingHistorySerializer
#
#     def get(self, request):
#         """
#         获取用户浏览的历史记录,这里其实就是查询后序列化输出就行
#         :param request: 请求携带的
#         :return: id(商品sku编号)  name(商品名称)  default_image_url(默认图片)  comments(评论量)
#         """
#         user_id = request.user.id
#         redis_conn = get_redis_connection('history')
#         history = redis_conn.lrange('history_%s' % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT-1)
#         skus = []
#         # 为了保持查询出的顺序与用户的浏览历史保存顺序一致
#         for sku_id in history:
#             skus.append(SKU.objects.get(pk=sku_id))
#         sku_info = SKUSerializer(skus, many=True)
#         return Response(sku_info.data)

class UserBrowsingHistoryView(ListCreateAPIView):
    """用户浏览历史记录的实现方式一"""
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.request.method == 'GET':
            # 其实就是回去浏览记录
            return SKUSerializer
        else:
            # 其实就POST请求,保存浏览记录
            return AddUserBrowsingHistorySerializer

    def get_queryset(self):
        user_id = self.request.user.id
        redis_conn = get_redis_connection('history')
        history = redis_conn.lrange('history_%s' % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)
        skus = []
        for sku_id in history:
            skus.append(SKU.objects.get(pk=int(sku_id)))
        return skus


class UserLoginView(ObtainJSONWebToken):
    """用户登录"""
    def post(self, request, *args, **kwargs):
        # 调用父类的方法,获取drf jwt扩展默认的认证用户处理结果
        response = super().post(request, *args, **kwargs)
        """
        登录逻辑还是使用jwt中的视图实现,此处在登录后添加自己的逻辑
        仿照drf jwt扩展对于用户登录的认证方式,判断用户是否认证登录成功
        如果用户登录认证成功,则合并购物车,此判断方式一如下:
        if response.status_code == 200:
            user = serializer.validated_data.get('user')
            response = merge_cart_cookie_to_redis(request, user, response)
        判断方式二如下:
        """
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 获取用户编号
            user = serializer.validated_data.get('user')
            # 当前添加逻辑: 合并购物车
            response = merge_cart_cookie_to_redis(request, user, response)

        return response
